<template>
    <div id="list">
        <el-table :data="courseTables" :height="tableHeight" :span-method="arraySpanMethod" border tooltip-effect="light">
            <el-table-column label="课程编号" align="left" min-width="90">
                <template slot-scope="props">
                    <div v-if="props.row.isCategoryRow">
                        <div
                            class="float-left"
                            style="display:inline-block;height:34px;line-height:34px;"
                        >
                            <i v-if="props.row.directionCode" style="margin-left:20px;">&nbsp;</i>
                            <span>{{ props.row.sequence }}{{ props.row.categoryName }}</span>
                        </div>
                        <div class="float-left" style="margin-left:40px;" v-if="!isRead">
                            <el-button
                                type="text"
                                @click="add(props.$index)"
                                v-if="props.row.showAddCourseBtn"
                            >新增课程</el-button>
                            <template v-if="dataType==2 && props.row.showAddCourseBtn">
                                <el-button
                                    type="text"
                                    @click="selectDirection()"
                                    v-if="!props.row.directionCode && props.row.hasCourse"
                                >分方向</el-button>
                                <el-button
                                    type="text"
                                    @click="deleteDirection(props.$index)"
                                    v-else-if="props.row.directionCode"
                                >删除方向</el-button>
                            </template>
                            <template v-if="props.row.hasCourse">
                                <el-button
                                    type="text"
                                    @click="showDivideModule(props.$index, 1)"
                                >分模块</el-button>
                                <el-button style="font-weight: 900;font-size: 14px;" type="text" @click="showDivideModule(props.$index, 2)">分组</el-button>
                            </template>
                        </div>
                    </div>
                    <div v-else>
                        <el-checkbox
                            v-model="courseTables[props.$index].isCourseCheck"
                            v-if="!isRead && props.row.isCourseRow && !props.row.courseGroupId && !props.row.parentId"
                            :key="props.row.id"
                            @change="pickCourse(props.row.id, props.$index, 1)"
                        ></el-checkbox>
                        <span>{{ props.row.code }}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column min-width="80" align="center" label="模块" show-overflow-tooltip style="position:relative;">
                <template slot-scope="props">
                    <el-checkbox
                        v-model="courseTables[props.$index].isModuleCheck"
                        v-if="!isRead && props.row.isCourseRow && props.row.courseGroupId && !props.row.parentId"
                        :key="props.row.courseGroupId"
                        @change="pickCourse(props.row.courseGroupId, props.$index, 2)"
                    ></el-checkbox>
                    <span>{{ props.row.remark }}</span>
                    <i
                        class="el-icon-delete"
                        @click="deleteGroup(props.row.courseGroupId)"
                        v-if="props.row.courseGroupId && !isRead"
                        style="color:red;cursor:pointer;position:absolute;right:4px;top:50%;margin-top:-6px;"
                        title="删除模块"
                    ></i>
                </template>
            </el-table-column>
            <el-table-column min-width="180" align="center" label="课程名称">
                <template slot-scope="props">
                    <a
                        @click="showCourseDetail(props.row)"
                        v-bind:class="{'new-record': inChange&&props.row.changeStatus == 1,'edit-record': inChange&&props.row.changeStatus == 2,'remove-record': inChange&&props.row.changeStatus == 3, }"
                    >{{ props.row.name }}</a>
                </template>
            </el-table-column>
            <el-table-column label="考试/查" align="center" width="90">
                <template slot-scope="props">
                    <el-select v-if="props.row.edit" v-model="currentRow.examMode" size="mini">
                        <el-option
                            v-for="item in options.types"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                    <span v-else>{{ props.row.examModeName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="学分" align="center" width="54">
                <template slot-scope="props">{{ props.row.studyScore }}</template>
            </el-table-column>
            <el-table-column label="学时/周数" align="center" width="85">
                <template
                    slot-scope="props"
                >{{ !!(props.row.weeks*1%17)?`${props.row.weeks}周`:props.row.weeks }}</template>
            </el-table-column>
            <el-table-column label="是否必修" align="center" width="80">
                <template
                    slot-scope="props"
                >{{ !props.row.compulsory?"":props.row.compulsory=='1'?"是":"否" }}</template>
            </el-table-column>
            <el-table-column label="上机时间" align="center" width="80">
                <template slot-scope="props">
                    <el-input v-if="props.row.edit" v-model="currentRow.computeTime" size="mini" type="number" :min="0"/>
                    <span v-else>{{ props.row.computeTime }}</span>
                </template>
            </el-table-column>
            <el-table-column label="实验时数" align="center" width="80">
                <template slot-scope="props">
                    <el-input
                        v-if="props.row.edit"
                        v-model="currentRow.experimentTime"
                        size="mini"
                        type="number"
                        :min="0"
                    />
                    <span v-else>{{ props.row.experimentTime }}</span>
                </template>
            </el-table-column>
            <el-table-column label="几选几" align="center" show-overflow-tooltip style="position:relative;">
                <template slot-scope="props">
                    <span>{{ props.row.parentRemark }}</span>
                    <i
                        class="el-icon-delete"
                        @click="deleteGroup(props.row.parentId)"
                        v-if="props.row.parentId && !isRead"
                        style="color:red;cursor:pointer;position:absolute;right:4px;top:50%;margin-top:-6px;"
                        title="删除课程分组"
                    ></i>
                </template>
            </el-table-column>
            <el-table-column label="各学期周学时分配/周数分配" align="center">
                <el-table-column :label="val" align="center" width="90" 
                    v-for="(val,idx) in semesterSorts" :key="'semester'+(idx+1)">
                    <template slot-scope="props">
                        <template v-if="props.row.edit">
                            <template v-if="currentRow.weeksType == 0">
                                <el-input v-model="currentRow['semester'+(idx+1)]" size="mini"
                                    type="number" @focus="autoSemesterValue(idx+1)"/>
                            </template>
                            <template v-else>
                                <el-select v-model="currentRow['semester'+(idx+1)]" clearable>
                                    <el-option
                                      v-for="(item,key) in semesterCodes"
                                      :key="key"
                                      :label="item"
                                      :value="key">
                                    </el-option>
                                </el-select>
                            </template>
                        </template>
                        <template v-else>
                            <span v-if="props.row.weeksType == 0">
                                {{ props.row['semester'+(idx+1)]}}
                            </span>
                            <span v-else>
                                {{ semesterCodes[props.row['semester'+(idx+1)]]}}
                            </span>
                        </template>
                    </template>
                </el-table-column>
            </el-table-column>
            <el-table-column label="备注" min-width="150" align="center">
                <template slot-scope="props">
                    <el-input
                        v-if="props.row.edit"
                        v-model="currentRow.remarks"
                        size="mini"
                        placeholder="请输入备注"
                    />
                    <span :title="props.row.remarks" v-else>{{ props.row.remarks }}</span>
                </template>
            </el-table-column>
            <el-table-column v-if="!isRead" label="操作" width="120" fixed="right">
                <template slot-scope="props">
                    <template v-if="props.row.isCourseRow">
                        <template v-if="props.row.edit">
                            <el-button type="text" @click="saveCourse(props.$index)">保存</el-button>
                            <el-button type="text" @click="cancelEdit(props.$index)">取消</el-button>
                        </template>
                        <template v-else>
                            <el-button type="text" @click="edit(props.$index)">编辑</el-button>
                            <el-button type="text" @click="remove(props.$index)">删除</el-button>
                        </template>
                    </template>
                </template>
            </el-table-column>
        </el-table>
        <el-row v-if="next" class="pd-12px float-right" style="padding-right: 0;">
            <el-col :span="24">
                <el-button size="medium" @click="next(-1)">上一步</el-button>
                <el-button size="medium" type="primary" @click="next()">下一步</el-button>
            </el-col>
        </el-row>

        <el-dialog
            :title="divideFormTitle"
            width="48%"
            :visible.sync="showDivideModuleDialog"
            style="padding:20px;"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
            <el-row :gutter="4">
                <el-col class="secondary-text">
                    <i class="el-icon-info" style="margin-top:4px;"></i>
                    <span>已选择{{curCheck.length}}{{divideModuleForm.level=='1'?"个模块":"门课程"}}</span>
                </el-col>
            </el-row>
            <el-table
                border
                style="margin-top:12px;"
                width="100%"
                :data="currentCourses"
                :height="180"
                :span-method="spanMethodForModule"
            >
                <el-table-column
                    label="模块"
                    align="center"
                    prop="remark"
                    v-if="divideModuleForm.level == '1'"
                />
                <el-table-column label="课程代码" align="center" prop="code"/>
                <el-table-column label="课程名称" align="center" prop="name"/>
                <el-table-column label="学分" align="center" prop="studyScore"/>
                <el-table-column label="总学时" align="center" prop="weeks"/>
                <!-- <el-table-column label="开课学院" align="center" prop="college"/> -->
                <el-table-column label="备注" align="center" prop="remarks"/>
            </el-table>
            <el-form
                :model="divideModuleForm"
                label-width="70px"
                label-position="right"
                ref="divideModuleForm"
                style="margin-top:12px;"
                :rules="rule"
                inline
            >
                <el-row>
                    <el-col :span="1">&nbsp;</el-col>
                    <el-col span="12" v-if="divideModuleForm.operate == 2">
                        <el-form-item label="课程组名" prop="remark">
                            <el-input
                                v-model="divideModuleForm.remark"
                                placeholder="请输入"
                                style="width:130px;"
                                size="mini"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col span="8" v-else>
                        <el-form-item label="模块名称" prop="remark">
                            <el-input
                                v-model="divideModuleForm.remark"
                                placeholder="请输入"
                                size="mini"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if="divideModuleForm.operate == 2">
                    <el-col :span="1">
                        <el-radio
                            v-model="limitType"
                            style="margin-top:8px;"
                            label="0"
                            @change="radioChoose"
                            :disabled="!canChangeLimitType"
                        >&nbsp;</el-radio>
                    </el-col>
                    <el-col :span="23">
                        <el-form-item label="门数限制:" prop="minNum">
                            <el-input-number
                                v-model="divideModuleForm.minNum"
                                @change="optionalChange"
                                :min="0"
                                :max="divideModuleForm.maxNum"
                                size="mini"
                                :disabled="limitType != '0'"
                                controls-position="right"
                            ></el-input-number>
                        </el-form-item>
                        <span>~&nbsp;&nbsp;</span>
                        <el-form-item prop="maxNum">
                            <el-input-number
                                v-model="divideModuleForm.maxNum"
                                @change="totalChange"
                                :min="divideModuleForm.minNum"
                                :max="100"
                                size="mini"
                                :disabled="limitType != '0'"
                                controls-position="right"
                            ></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="1">
                        <el-radio
                            v-model="limitType"
                            style="margin-top:8px;"
                            label="1"
                            @change="radioChoose"
                            :disabled="!canChangeLimitType"
                        >&nbsp;</el-radio>
                    </el-col>
                    <el-col :span="23">
                        <el-form-item label="学分限制:" prop="expression">
                            <el-select
                                v-model="divideModuleForm.expression"
                                size="mini"
                                style="width:130px;"
                                :disabled="limitType != '1'"
                            >
                                <el-option
                                    v-for="item in options.expressions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="minCredits">
                            <el-input
                                v-model="divideModuleForm.minCredits"
                                size="mini"
                                style="width:50px;"
                                :disabled="limitType != '1'"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer">
                <div style="margin:12px">
                    <el-button @click="showDivideModuleDialog = false">{{$t('message.cancel')}}</el-button>
                    <el-button
                        type="primary"
                        @click="writeDivideRelation()"
                    >{{$t('message.confirm')}}</el-button>
                </div>
            </span>
        </el-dialog>
        <courses
            ref="courseDialog"
            :random-id="randomId"
            :show="showCourseDialog"
            :is-elective="isElectiveForCurRow"
        />

        <el-dialog title="划分方向" width="42%" :visible.sync="showDirectionDialog" :close-on-click-modal="false"
            :close-on-press-escape="false">
            <el-form :model="directionForm" label-position="right" ref="directionForm">
                <el-row>
                    <el-col>
                        <el-form-item label="方向:">
                            <el-select v-model="directionForm.directionCode" size="mini">
                                <el-option
                                    v-for="item in options.directions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer">
                <div style="margin:12px">
                    <el-button @click="showDirectionDialog = false">{{$t('message.cancel')}}</el-button>
                    <el-button type="primary" @click="writeDirectionRel()">{{$t('message.confirm')}}</el-button>
                </div>
            </span>
        </el-dialog>
        <courseDetail
            :couseDetail="couseDetail"
            :showCourseDialog="showCourseDetailDialog"
            @closeCourseDialog="handlerCloseCourseDialog"
            lang="cn"
            v-if="showCourseDetailDialog"
        ></courseDetail>
    </div>
</template>
<script>
import {
    courseLabelRelation,
    addCourse,
    EditCourse,
    deleteCourse,
    getCourseList
} from "common/src/api/courseTemplate";
import {
    addCourseLabelRelGroup,
    findDirectionDataByScheme,
    addDirectionLableRelToCourse,
    delDirectionLableRelToCourse,
    deleteCourseLabelRelGroup
} from "common/src/api/culture/cultruescheme";
import { queryDic } from "common/src/api/dictionary";
import Bus from "common/src/utils/bus";

import courses from "./courses";
import courseDetail from "common/src/views/culture/common/courseDetail";
export default {
    props: {
        next: {
            type: Function,
            default: null //下一步方法
        },
        templateId: {
            default: null //当前模板Id
        },
        isRead: {
            default: false //操作列是否可见
        },
        dataType: {
            default: "1" //1为模板，2为方案
        },
        inChange: {
            type: Boolean,
            default: false
        },
        showSCteachArrangements: {//强化班教学安排 设置高度使用，其他地方不会用到
            type: Boolean,
            default: false
        }
    },
    name: "courseForm",
    components: {
        courses: courses,
        courseDetail
    },
    data() {
        const validate = (rule, value, callback) => {
            let flag = value === "";
            flag =
                flag &&
                ((this.limitType == "0" &&
                    (rule.field == "minNum" || rule.field == "maxNum")) ||
                    (this.limitType == "1" &&
                        (rule.field == "expression" ||
                            rule.field == "minCredits")));
            if (!flag) callback();
            else callback(new Error("请输入字段"));
        };
        const validateMinCredits = (rule, value, callback) => {
            let flag = this.limitType == "1" && isNaN(value);
            if (!flag) callback();
            else callback(new Error("请输入字段"));
        };
        const verifyName = (rule, value, callback) => {
            if (value.trim() != "") callback();
            else
                callback(
                    new Error(
                        `请输入${this.moduleType == 1 ? "模块" : "课程组"}名称`
                    )
                );
        };
        return {
            moduleType: 1,
            showDirectionDialog: false,
            dialogTitle: "",
            showDivideModuleDialog: false,
            divideModuleForm: {
                operate: "",
                courseIdList: [],
                remark: "",
                level: "",
                type: "0",
                minNum: "",
                maxNum: "",
                minCredits: "",
                expression: ""
            },
            curCheck: [],
            spanDataForModule: [],
            spanDataForGroup: [],
            randomId: "", //用于事件监听和注销，确保唯一性
            tableHeight: 420,
            rowData: null, //获取原始数据,包括课程分类和课程列表
            showCourseDialog: false,
            isElectiveForCurRow: "",
            courseTables: [],
            currentRow: {}, //当前操作行,新增/编辑/删除时，保存当前操作行
            isAdd:true,//是否添加课程
            options: {
                types: [],
                directions: [],
                expressions: [
                    { label: "大于等于", value: "1" },
                    { label: "等于", value: "2" }
                ]
            },
            directionForm: {
                directionCode: ""
            },
            limitType: "0",
            canChangeLimitType: true,
            currentCourses: [],
            spanData: [],
            divideFormTitle: "",
            rule: {
                remark: [{ validator: verifyName, trigger: "blur" }],
                minNum: [{ validator: validate, trigger: "blur" }],
                maxNum: [{ validator: validate, trigger: "blur" }],
                expression: [{ validator: validate, trigger: "blur" }],
                minCredits: [
                    { validator: validate, trigger: "blur" },
                    { validator: validateMinCredits, trigger: "blur" }
                ]
            },
            showCourseDetailDialog: false,
            couseDetail: {},
            semesterSorts: ['一','二','三','四','五','六','七','八','九','十'],
            semesterCodes: {'999': '暑期'}
        };
    },
    created() {
        this.randomId = "courseDialogEvent" + new Date().getTime();
        //计算table的height值
        let elMain = document.getElementsByClassName("el-main");
        if (elMain && elMain.length > 0) {
            this.tableHeight = elMain[0].clientHeight - 140;
        }
        if (this.showSCteachArrangements && elMain && elMain.length > 0) {
            this.tableHeight = elMain[0].clientHeight - 300;//这是设置强化班教学安排高度
        }
        //接受选择课程的信息
        Bus.$on(this.randomId, (state,status, courses) => {
            this.showCourseDialog = state;
            this.isAdd = status;
            if (courses) this.addCourseForLabel(courses);
        });
    },
    beforeDestroy() {
        Bus.$off(this.randomId);
    },
    mounted() {
        this.initOptions();
        this.init();
    },
    methods: {
        radioChoose() {
            this.$refs.divideModuleForm.clearValidate();
        },
        deleteGroup(id) {
            this.$confirm("此操作将删除分组或模块, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                deleteCourseLabelRelGroup({ id: id })
                    .then(res => {
                        if (res.code == 200) {
                            this.$message({
                                type: "success",
                                message: "删除成功"
                            });
                            this.init();
                        }
                    })
                    .catch(err => {
                        this.$message({
                            type: "error",
                            message: "删除失败"
                        });
                        console.log(err);
                    });
            });
        },
        writeDirectionRel() {
            this.directionForm.courseRelIds = this.curCheck;
            addDirectionLableRelToCourse(this.directionForm)
                .then(res => {
                    if (res.code == 200) {
                        this.$message({
                            type: "success",
                            message: "操作成功"
                        });
                        this.init();
                        this.showDirectionDialog = false;
                    }
                })
                .catch(err => {
                    this.$message({
                        type: "error",
                        message: "操作失败"
                    });
                });
        },
        deleteDirection(index) {
            let param = this.getDeleteDirectionParam(index);
            this.$confirm("此操作将删除方向及其课程, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                this.doDeleteDirection(param);
            });
        },
        doDeleteDirection(param) {
            delDirectionLableRelToCourse(param)
                .then(res => {
                    if (res.code == 200) {
                        this.$message({
                            type: "success",
                            message: "删除成功"
                        });
                        this.init();
                    }
                })
                .catch(err => {
                    this.$message({
                        type: "error",
                        message: "删除失败"
                    });
                    console.log(err);
                });
        },
        getDeleteDirectionParam(index) {
            let directionCode = this.courseTables[index].directionCode;
            let courseRelIds = this.courseTables.filter(e => {
                return !e.isCategoryRow && e.directionCode == directionCode;
            });
            return {
                directionCode: directionCode,
                courseRelIds: courseRelIds.map(e => e.id)
            };
        },
        selectDirection() {
            if (this.curCheck.length == 0) {
                this.$message({
                    type: "warning",
                    message: "请选择要划分方向的课程或分组"
                });
                return;
            }
            this.loadDirections();
            this.showDirectionDialog = true;
        },
        loadDirections() {
            findDirectionDataByScheme(this.templateId).then(res => {
                if (res.code == 200) {
                    this.options.directions = res.data.map(e => {
                        return {
                            label: e.directionName,
                            value: e.directionCode
                        };
                    });
                }
            });
        },
        add(index) {
            this.currentRow = Object.assign({}, this.courseTables[index]);
            this.showCourseDialog = true;
            // this.$refs.courseDialog.queryCourseForm.isElective = this.currentRow.isElective;
            this.isElectiveForCurRow = this.currentRow.isElective;
            setTimeout(() => {
                this.$refs.courseDialog.onSubmit();
            }, 100);
        },
        edit(index) {
            if(!!this.currentRow && Object.keys(this.currentRow).length != 0 && !this.isAdd) {
                this.$message({
                    type: "error",
                    message: "请先取消/保存数据"
                });
                return;
            }
            this.currentRow = Object.assign({}, this.courseTables[index]);
            this.courseTables[index].edit = true;
            this.isAdd = false
            this.currentRow.examMode = String(this.currentRow.examMode);
        },
        saveCourse() {
            let data = Object.assign({}, this.currentRow);
            data.trainingId = this.templateId;
            data.type = this.dataType;
            if (this.inChange) data.changeStatus = "2";
            EditCourse(data).then(res => {
                if (res.code == 200) {
                    this.$message({
                        type: "success",
                        message: "保存成功"
                    });
                    this.currentRow = {};
                    this.init();
                }
            });
        },
        cancelEdit(index) {
            this.courseTables[index].edit = false;
            this.isAdd = true;
            this.currentRow = {};
        },
        addCourseForLabel(courses) {
            let data = this.getAddData(courses);
            addCourse(data).then(res => {
                if (res.code == 200) {
                    this.$message({
                        type: "success",
                        message: "添加成功"
                    });
                    this.init();
                }
            });
        },
        getAddData(courses) {
            courses.courseCodes = courses.item.map(item => {
                return item.code;
            });
            courses.trainingId = this.templateId;
            courses.type = this.dataType;
            courses.labelId = this.currentRow.labelId;
            if (
                this.currentRow.hasOwnProperty("directionCode") &&
                this.currentRow.directionCode != ""
            )
                courses.chan.directionCode = this.currentRow.directionCode;
            if (this.inChange) courses.changeStatus = "1";
            delete courses.item;
            return courses;
        },
        pickCourse(id, index, level) {
            if (event.target.checked && this.canCheck(id, index, level))
                this.curCheck.push(id);
              
            else {
                if (this.curCheck.indexOf(id) >= 0)
                    this.curCheck.splice(this.curCheck.indexOf(id), 1);
                this.courseTables[index].isCourseCheck = false;
                this.courseTables[index].isModuleCheck = false;
            }
            if (this.curCheck.length == 0) {
                this.divideModuleForm.level = "";
            }
        },
        canCheck(id, index, level) {
            if (
                this.divideModuleForm.level != "" &&
                level != this.divideModuleForm.level
            ) {
                this.$message({
                    message: "不能同时选择模块和课程",
                    type: "warning"
                });
                return false;
            }
            if (this.curCheck.length == 0) {
                this.divideModuleForm.level = level;
                return true;
            } else {
                if (this.isSameType(id, level)) {
                    return true;
                } else {
                    this.$message({
                        message: "请选择同一类型下的课程",
                        type: "warning"
                    });
                    return false;
                }
            }
        },
        isSameType(id, level) {
            return (
                this.getParentId(this.curCheck[0], level) ==
                    this.getParentId(id, level) &&
                this.getDirection(this.curCheck[0], level) ==
                    this.getDirection(id, level)
            );
        },
        getDirection(id, level) {
            return this.courseTables.filter(item => {
                return level == 1 ? item.id == id : item.courseGroupId == id;
            })[0].directionCode;
        },
        getParentId(id, level) {
            return this.courseTables.filter(item => {
                return level == 1 ? item.id == id : item.courseGroupId == id;
            })[0].labelId;
        },
        showDivideModule(index, type) {
            if (this.curCheck.length == 0) {
                this.$message({
                    message: "请选择要进行分组的课程或者模块",
                    type: "warning"
                });
                return;
            }
            if (this.divideModuleForm.level == 2 && type == 1) {
                this.$message({
                    message: "模块不能再次划分模块",
                    type: "warning"
                });
                return;
            }
            this.divideFormTitle = type == 1 ? "划分模块" : "课程分组";
            this.moduleType = type;
            this.setCurrentCourses();
            this.setDivideForm(index, type);
            this.showDivideModuleDialog = true;
        },
        setCurrentCourses() {
            if (this.divideModuleForm.level == 2) {
                let count = 0;
                this.curCheck.forEach(e => {
                    let span = {
                        rowIndex: count
                    };
                    this.courseTables.forEach(i => {
                        if (i.courseGroupId == e) {
                            this.currentCourses.push(i);
                            count++;
                        }
                    });
                    span.rowspan = count - span.rowIndex;
                    this.spanData.push(span);
                });
            } else
                this.currentCourses = this.curCheck.map(e => {
                    return this.courseTables.find(i => {
                        return i.id == e;
                    });
                });
        },
        setDivideForm(index, type) {
            this.divideModuleForm.operate = type;
            this.currentRow = this.courseTables[index];
            if (this.currentRow.limitType) {
                this.canChangeLimitType = false;
                this.limitType = this.currentRow.limitType;
            }
            let level = this.divideModuleForm.level;
            //课程分模块
            if (level == 1 && type == 1) this.divideModuleForm.level = 3;
            //课程分组
            else if (level == 1 && type == 2) this.divideModuleForm.level = 2;
            //模块分组
            else if (level == 2 && type == 2) this.divideModuleForm.level = 1;
        },
        writeDivideRelation() {
            this.divideModuleForm.courseIdList = this.curCheck;
            this.$refs["divideModuleForm"].validate(valid => {
                if (valid) {
                    this.divideModuleForm.type = this.limitType;
                    addCourseLabelRelGroup(this.divideModuleForm).then(res => {
                        if (res.code == 200) {
                            this.$message({
                                message: "操作成功",
                                type: "success"
                            });
                            this.resetPage();
                            this.init();
                        }
                    });
                } else return false;
            });
        },
        resetPage() {
            this.curCheck = [];
            this.canChangeLimitType = true;
            this.limitType = "0";
            this.showDivideModuleDialog = false;
        },
        initOptions() {
            let data = {
                lang: this.$store.getters.language || "cn",
                type: "allChild",
                keys: ["X_KSLX"]
            };
            queryDic(data)
                .then(res => {
                    if (res.code == 200) {
                        this.loadOptions("types", res.data.X_KSLX);
                    }
                })
                .catch(err => {
                    this.$message({
                        type: "error",
                        message: "查询失败"
                    });
                });
        },
        loadOptions(optionKey, dataObj) {
            for (let key in dataObj) {
                this.options[optionKey].push({
                    value: key,
                    label: dataObj[key]
                });
            }
        },
        remove(index) {
            let row = this.courseTables[index];
            if (row.courseGroupId != "" || row.parentId != "") {
                this.$message({
                    message: "已经分组或者分模块的课程不能删除",
                    type: "warning"
                });
                return;
            }
            this.$confirm("是否删除该课程?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                deleteCourse(row.id).then(res => {
                    if (res.code == 200) {
                        this.$message({
                            type: "success",
                            message: "删除成功!"
                        });
                        this.init();
                    } else if (res.code == 300) {
                        this.$message({
                            type: "warning",
                            message: "不能删除该条记录!"
                        });
                    }
                });
            });
        },

        //获取后台相关课程数据(初始化页面数据)
        init() {
            this.rowData = {};
            this.rowData.courseCategories = [];
            courseLabelRelation(this.templateId, this.dataType).then(res => {
                    if (res.code == 200) {
                        this.setCategoryData(res.data.coursesLabelList);
                        this.setCourseData(res.data.courseLabelRelationList);
                        this.rowData.directions = res.data.directionList;
                        this.convert();
                    }
                }).catch(e => {
                    this.$message({ type: "error", message: "查询课程表单失败" });
                });
        },


        setCategoryData(list) {
            this.rowData.courseCategories = list.map(c => {
                return {
                    id: c.labelId,
                    name: c.label,
                    labelId: c.parentId,
                    isElective: c.isElective,
                    limitType: c.limitType
                };
            });
        },
        setCourseData(list) {
            this.rowData.courses = [];
            list.forEach(ele => {
                ele.examModeName = this.getExamModeTextByValue(ele.examMode);
                ele.isCourseRow = true;
                ele.isCourseCheck = false;
                ele.isModuleCheck = false;
                ele.edit = false;
                ele.studyScore = ele.credits;
                ele.parentId =
                    ele.levelType == 2 ? ele.courseGroupId : ele.parentId;
                ele.courseGroupId = ele.levelType == 2 ? "" : ele.courseGroupId;
                this.rowData.courses.push(Object.assign({}, ele));
            });
        },
        //转换原生数据为渲染数据
        convert() {
            let viewData = [];
            this.appendCategory(viewData, 0);
            this.courseTables = viewData;
            this.spanDataForModule = this.getspanData(1);
            this.spanDataForGroup = this.getspanData(2);
        },
        //添加分类项
        appendCategory(viewData, pid) {
            let categories = this.rowData.courseCategories.filter(
                c => c.labelId == pid
            );
            categories.forEach((c, index) => {
                let childCategory = this.rowData.courseCategories.find(
                    c_ => c_.labelId == c.id
                );
                let category = {
                    sequence:
                        pid == 0
                            ? this.$utils.numberToChinese(index + 1) + "、"
                            : "",
                    categoryName: c.name,
                    labelId: c.id,
                    isCategoryRow: true,
                    isElective: c.isElective, //是否公共选修
                    showAddCourseBtn: !childCategory,
                    hasCourse: this.hasCourse(c.id)
                };
                viewData.push(category);
                if (childCategory) this.appendCategory(viewData, c.id);
                else
                    this.appendCourse(
                        viewData,
                        c.id,
                        c.isElective,
                        c.limitType
                    );
            });
        },
        /**是否有课程 */
        hasCourse(labelId) {
            return this.rowData.courses.some(i => {
                return i.labelId == labelId && i.directionCode == "";
            });
        },
        //添加课程项
        appendCourse(viewData, courseCategoryId, isElective = "", limitType) {
            let directs = {};
            this.rowData.courses.forEach(course => {
                if (course.labelId == courseCategoryId) {
                    let row = Object.assign({}, course);
                    row.labelId = courseCategoryId;
                    row.isElective = isElective; ////是否公共选修
                    if (course.isDirection == "0") {
                        viewData.push(row);
                    } else if (course.isDirection == "1") {
                        if (!directs[row.directionCode])
                            directs[row.directionCode] = [];
                        directs[row.directionCode].push(row);
                    }
                }
            });
            // this.appendNewRow(viewData, courseCategoryId, isElective);
            this.appendDirection(
                viewData,
                courseCategoryId,
                directs,
                isElective,
                limitType
            );
        },
        appendDirection(
            viewData,
            courseCategoryId,
            directs,
            isElective,
            limitType
        ) {
            for (let key in directs) {
                let direct = this.rowData.directions.find(e => {
                    return e.code == key;
                });
                if (direct) {
                    viewData.push({
                        labelId: courseCategoryId,
                        directionCode: direct.code,
                        categoryName: direct.name,
                        isCategoryRow: true,
                        isElective: isElective, //是否公共选修
                        hasCourse: directs[key].length > 0,
                        limitType: limitType,
                        showAddCourseBtn: true
                    });
                    directs[key].forEach(e => {
                        viewData.push(e);
                    });
                    // this.appendNewRow(viewData, courseCategoryId, isElective, key);
                }
            }
        },
        appendNewRow(viewData, courseCategoryId, isElective, direction) {
            let addRow = {
                isAddRow: true,
                labelId: courseCategoryId,
                isElective: isElective
            };
            if (direction) addRow.directionCode = direction;
            viewData.push(addRow);
        },
        spanMethodForModule({ row, column, rowIndex, columnIndex }) {
            if (columnIndex == 0) {
                let d = this.spanData.filter(ele => {
                    return ele.rowIndex == rowIndex;
                });
                if (d.length > 0) {
                    return {
                        rowspan: d[0].rowspan,
                        colspan: 1
                    };
                } else {
                    if (this.divideModuleForm.level == 1)
                        return {
                            rowspan: 0,
                            colspan: 1
                        };
                    else
                        return {
                            rowspan: 1,
                            colspan: 1
                        };
                }
            }
        },
        //合并单元计算
        arraySpanMethod({ row, column, rowIndex, columnIndex }) {
            if (row.isCategoryRow) {
                return {
                    rowspan: 1,
                    colspan: this.isRead ? 21 : 22 //根据操作列是否可见，计算课程分类合并列
                };
            }
            if (columnIndex == 1 || columnIndex == 9) {
                let spanData =
                    columnIndex == 1
                        ? this.spanDataForModule
                        : this.spanDataForGroup;
                let d = spanData.filter(ele => {
                    return ele.rowIndex == rowIndex;
                });
                if (d.length > 0) {
                    return {
                        rowspan: d[0].rowspan,
                        colspan: 1
                    };
                }
            }
        },
        getspanData(type) {
            //type==1 分模块, type ==2 分组
            let labelId = type == 1 ? "courseGroupId" : "parentId";
            let curPid = -1,
                curRowIndex,
                rowspan,
                spanData = [];
            this.courseTables.forEach((ele, i, arr) => {
                if (ele.isCourseRow && ele[labelId]) {
                    if (ele[labelId] != curPid) {
                        if (curPid != -1) {
                            spanData.push({
                                rowIndex: curRowIndex,
                                rowspan: rowspan
                            });
                        }
                        curPid = ele[labelId];
                        curRowIndex = i;
                        rowspan = 1;
                    } else {
                        spanData.push({
                            rowIndex: i,
                            rowspan: 0
                        });
                        rowspan++;
                    }
                }
            });
            spanData.push({
                rowIndex: curRowIndex,
                rowspan: rowspan
            });
            return spanData;
        },
        getExamModeTextByValue(value) {
            let item = this.options.types.find(t => t.value == value);
            if (item) return item.label;
            else return "";
        },
        showCourseDetail(c) {
            this.couseDetail = {
                ...c,
                week_hour: c.weekHour
            };
            this.showCourseDetailDialog = true;
        },
        handlerCloseCourseDialog() {
            this.showCourseDetailDialog = false;
        },
        autoSemesterValue(idx) {
            if(!this.currentRow['semester'+idx]) {
                if(this.currentRow.weeksType == 0) {// 教学周
                    this.currentRow['semester'+idx] = this.currentRow.studyScore;
                } else if(this.currentRow.weeksType == 1) {// 实践周
                    return
                } else {
                   // 不做处理
                }
            }
        }
    },
    watch: {
        showDivideModuleDialog: function(n, o) {
            if (!n) {
                this.init();
                this.curCheck = [];
                this.divideModuleForm.level = "";
                this.divideModuleForm.courseIdList = [];
                // this.divideModuleForm.remark = "";
                this.divideModuleForm.operate = "";
                this.$refs.divideModuleForm.resetFields();
                this.currentCourses = [];
                this.currentRow = null;
            }
        },
        showDirectionDialog: function(_n, _o) {
            if (!_n) {
                this.directionForm.directionCode = "";
                this.directionForm.courseIdList = [];
                this.curCheck = [];
                this.init();
            }
        }
    }
};
</script>
